package com.rahms.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rahms.pojo.entity.SystemMessage;
import com.rahms.server.mapper.SystemMessageMapper;
import com.rahms.server.service.SystemMessageService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 系统消息服务实现类
 */
@Service
public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, SystemMessage> implements SystemMessageService {
    
    @Override
    public List<SystemMessage> getMessagesByRecipientId(Long recipientId, String msgType, Integer isRead) {
        LambdaQueryWrapper<SystemMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemMessage::getRecipientId, recipientId)
                   .eq(msgType != null && !msgType.isEmpty(), SystemMessage::getMsgType, msgType)
                   .eq(isRead != null, SystemMessage::getIsRead, isRead)
                   .orderByDesc(SystemMessage::getSendTime);
        return this.list(queryWrapper);
    }
    
    @Override
    public boolean sendSystemMessage(SystemMessage message) {
        if (message == null) {
            return false;
        }
        
        message.setIsRead(0);  // 默认未读
        message.setSendTime(LocalDateTime.now());
        
        // 如果没有设置过期时间，默认设置为7天后
        if (message.getExpireTime() == null) {
            message.setExpireTime(LocalDateTime.now().plusDays(7));
        }
        
        return this.save(message);
    }
    
    @Override
    public boolean markMessageAsRead(Long messageId) {
        SystemMessage message = this.getById(messageId);
        if (message != null) {
            message.setIsRead(1);
            return this.updateById(message);
        }
        return false;
    }
}